package services;

import java.util.Collection;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import repositories.VacancyRepository;
import domain.Project;
import domain.Vacancy;
import forms.VacancyForm;

@Service
@Transactional
public class VacancyService {
	@Autowired
	private UserService userService;
	@Autowired
	private VacancyRepository vacancyRepository;

	@Autowired
	private ProjectService projectService;

	public Vacancy create(Project project) {
		Vacancy result;
		
		Assert.notNull(project);
		Assert.isTrue(project.getCreator()
				.equals(userService.findByPrincipal()));
		Assert.isTrue(project.getStatus().equals("Creating"));
		
		result = new Vacancy();
		
		result.setProject(project);
		return result;
	}

	public void save(Vacancy vacancy) {
		int totalPeopleRequired;
		
		Assert.notNull(vacancy);
		Assert.isTrue(vacancy.getProject().getStatus().equals("Creating"));
		
		
		if(vacancy.getId() == 0){
			totalPeopleRequired = vacancy.getPeopleRequired();
			vacancy.setTotalPeopleRequired(totalPeopleRequired);
		}
		vacancyRepository.save(vacancy);
	}

	public Vacancy findOne(int vacancyId) {
		Assert.isTrue(vacancyId != 0);
		Vacancy result;
		
		result = vacancyRepository.findOne(vacancyId);
		
		return result;
	}

	public Vacancy reconstruct(VacancyForm vacancyForm) {
		Assert.notNull(vacancyForm);
		
		Vacancy result;
		Project project;
		
		project = projectService.findOne(vacancyForm.getProjectId());
		result = create(project);
		result.setPeopleRequired(vacancyForm.getPeopleRequired());
		result.setUserGroup(vacancyForm.getUserGroup());

		return result;
	}

	public Collection<Vacancy> findByProject(int projectId) {
		Collection<Vacancy> result;
		
		result = vacancyRepository.findByProject(projectId);
		
		return result;
	}
	
	public Vacancy findByProjectAndGroupId(int projectId, int userGroupId){
		Vacancy result;
		
		Assert.isTrue(projectId != 0);
		Assert.isTrue(userGroupId != 0);
		result = vacancyRepository.findByProjectAndGroupId(projectId, userGroupId);
		
		return result;
	}

}
